package com.yc.web.core.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableKnife4j  // 使用 Knife4j 专用注解
public class Knife4jConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yc.web.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .groupName("0.7版本")
                .pathMapping("/");
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Document_Management_Platform API")
                .description("文件管理平台-API文档")
                .version("v0.7")
                .contact(new Contact("IT_Yan", "http://your-website.com", "1872752462@qq.com"))
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        // 设置请求头信息
        List<SecurityScheme> result = new ArrayList<>();

        // 添加访问令牌头
        SecurityScheme securityScheme = new ApiKey("Authorization", "Authorization", "header");
        result.add(securityScheme);

        // 添加刷新令牌头
        SecurityScheme refreshTokenScheme = new ApiKey("Refresh-Token", "Refresh-Token", "header");
        result.add(refreshTokenScheme);

        return result;
    }

    private SecurityContext getContextByPath(String pathRegex) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> result = new ArrayList<>();

        // 定义匿名访问的路径集合，与SecurityConfig中permitAll的路径保持一致
        String[] anonymousPaths = {
                "/getCaptchaId",
                "/getCaptchaImage/.*",
                "/login",
                "/register",
                "/doc.html",
                "/swagger-resources/.*",
                "/webjars/.*",
                "/v3/api-docs/.*",
        };

        // 添加需要认证的路径
        result.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(path -> {
                    // 检查当前路径是否在匿名路径列表中
                    for (String pattern : anonymousPaths) {
                        if (path.matches(pattern)) {
                            return false; // 匿名路径，不需要认证
                        }
                    }
                    return true; // 不在匿名路径列表中，需要认证
                })
                .build());

        return result;
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }
}